package com.szt.ynb.server.router.controller.manage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.szt.ynb.server.router.common.SessionConst;
import com.szt.ynb.server.router.entity.Log;
import com.szt.ynb.server.router.entity.User;
import com.szt.ynb.server.router.entity.enums.LogType;
import com.szt.ynb.server.router.pojo.SessionUser;
import com.szt.ynb.server.router.service.LogService;
import com.szt.ynb.server.router.service.UserService;
import com.szt.ynb.server.router.utils.IpUtils;
import com.szt.ynb.server.router.vo.base.RepBaseVO;

@Controller
@RequestMapping("manage/main")
public class ManageMainController {
	
	private static final Logger LOG = LoggerFactory.getLogger(ManageMainController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private LogService logService;
	
	@GetMapping("login")
	public String loginPage() {
		return "index";
	}
	
	@SuppressWarnings("rawtypes")
	@PostMapping("login")
	@ResponseBody
	public RepBaseVO loginAction(String username, String password, HttpSession httpSession,
			HttpServletRequest request) {
		RepBaseVO repVO = new RepBaseVO<>();
		User user = userService.findByUsername(username);
		if (user == null) {
			return repVO.setCommonFail().setMes("用户名或者密码错误");
		}
		System.out.println(DigestUtils.sha256Hex(password));
		if (!DigestUtils.sha256Hex(password).equals(user.getPassword())) {
			return repVO.setCommonFail().setMes("用户名或者密码错误");
		}
		httpSession.setAttribute(SessionConst.SESSION_ADMIN, new SessionUser(user, IpUtils.getIpAddr(request)));
		logService.save(new Log(user.getId(), "登陆成功", LogType.SIMPLE, IpUtils.getIpAddr(request)));
		return repVO.setCommonSuccess();
	}
}
